package match

import (
	"math/rand"
	"sync"
)

// userMatchManagerRegionUserManager 单独一个区域的单独管理器
type userMatchManagerRegionUserManager struct {
	RegionName string          `json:"region_name"` // 区域id
	Count      int64           `json:"count"`       // 区域人数
	Locker     sync.Mutex      `json:"locker"`      // 锁
	UserMap    map[int64]int64 `json:"user_map"`    // 用户映射
}

func newUserMatchManagerRegionUserManager(name string) *userMatchManagerRegionUserManager {
	return &userMatchManagerRegionUserManager{
		RegionName: name,
		UserMap:    make(map[int64]int64),
	}
}

// Online 标记用户在线
func (u *userMatchManagerRegionUserManager) Online(userId int64) {
	u.Locker.Lock()
	defer u.Locker.Unlock()

	u.UserMap[userId] = userId
}

// Leave 标记用户离线
func (u *userMatchManagerRegionUserManager) Leave(userId int64) {
	u.Locker.Lock()
	defer u.Locker.Unlock()

	delete(u.UserMap, userId)
}

// Match 匹配在线用户
func (u *userMatchManagerRegionUserManager) Match(roleId int64) int64 {
	u.Locker.Lock()
	defer u.Locker.Unlock()

	var allCnt = len(u.UserMap)
	if allCnt == 0 {
		return 0
	}

	// 随机取出一个id
	taskCnt := 0
	for true {
		taskCnt++
		randNum := rand.Intn(allCnt)
		actionId := u.UserMap[int64(randNum)]

		if actionId != roleId {
			return actionId
		}

		if taskCnt > 3 {
			break
		}
	}

	return 0
}
